﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace ButtonTree2
{
    public static class GrayscaleImagesUtil
    {
        //对于彩色转灰度，有一个很著名的心理学 公式：
        //Gray = R*0.299 + G*0.587 + B*0.114
//         private const float GrayRed = 0.3086f;
//         private const float GrayGreen = 0.6094f;
//         private const float GrayBlue = 0.082f;
        private const float GrayRed = 0.299f;
        private const float GrayGreen = 0.587f;
        private const float GrayBlue = 0.114f;


        private static float[][] matrix;
        private static ImageAttributes imageAttr;


        static GrayscaleImagesUtil()
        {
            matrix = new float[][]{  
                new float[] {GrayRed, GrayRed, GrayRed, 0, 0},
                new float[] {GrayGreen, GrayGreen, GrayGreen, 0, 0},
                new float[] {GrayBlue, GrayBlue, GrayBlue, 0, 0},
                new float[] {0, 0, 0, 1, 0},
                new float[] {0, 0, 0, 0, 1}
            };
            ColorMatrix cm = new ColorMatrix(matrix);
            imageAttr = new ImageAttributes();
            imageAttr.SetColorMatrix(cm);
        }

        public static void DrawImage(Graphics g, Image image, Rectangle rect)   // 显示灰度图
        {
            g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttr);
        }
    }
}
